package yxy.game.pm2.command.conquest;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ConquestMessage;
import yxy.game.pm2.module.conquest.ConquestHandle;
import yxy.game.pm2.module.hero.FormatHandle;

import java.util.Date;


/**
 * 征战 挑战敌将
 */
@MessageType(proto = Command.ConquestEnemy, classtype = ConquestMessage.ConquestEnemyRequest.class)
public class CMD_ConquestEnemy extends Command<ConquestMessage.ConquestEnemyRequest> {

    @Override
    public void execute(MessageSource messageSource, ConquestMessage.ConquestEnemyRequest request) {
        Date date1 = new Date();

        ConquestMessage.ConquestEnemyResponse.Builder response = ConquestMessage.ConquestEnemyResponse.newBuilder();
        try {

            String playerCode = messageSource.getTag();
            ConquestHandle handle = new ConquestHandle();
            if (handle.isBattling(playerCode)) {
                send(messageSource, response, Result.BattleIsRunning);// 还有正在进行中的战斗
                return;
            }

            FormatHandle formatHandle = new FormatHandle();
            Result result = formatHandle.check(playerCode, formatHandle.get(playerCode, Format.FormatType.普通));
            if (!result.equals(Result.Success)) {
                send(messageSource, response, result);   //  重复武将判断
                return;
            }

            response.setBattle(handle.battleResponse(playerCode));
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }

        Date date2 = new Date();
        System.out.println("CMD_ConquestEnemy:" + (date2.getTime() - date1.getTime()));

    }

    private void send(MessageSource messageSource, ConquestMessage.ConquestEnemyResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}